<?php

//linux 下文件路径设置
ini_set("include_path",".:/var/www/html/swaylink:");
require_once("ThinkPHP/Library/Vendor/Sms/TopSdk.php");
require_once("ThinkPHP/Library/Vendor/SendEmail.php");
require_once("ThinkPHP/Library/Vendor/JPush/autoload.php");
/**
 * redis操作
 */
class MRedis{
//     swaylink数据库配置
//     const DB_HOST = 'rm-2ze8dsb9dg15b60e8.mysql.rds.aliyuncs.com';
//     const DB_USER = 'swaylink_root';
//     const DB_PWD = '123!Swaylink';
//     const DB_NAME = 'swaylink_db';
    
//     mydeihui数据库配置项
    const DB_HOST = '101.200.155.51';
    const DB_USER = 'root';
    const DB_PWD = '!Swaylink123';
    const DB_NAME = 'swaylink_db';
    //多长时间未操作为掉线(秒)
    const CHECK_TIME = '330';
    //延迟多少秒执行
    const SLEEP_TIME = '1800';
    //是否开启短信推送
    const ALARM_SMS = false;
    //是否开启APP消息推送
    const AlARM_APP = true;

    //微信配置
    const APPID = "wx97e68d4a0c3f2814";
    const APPSECRET = "1ff5aac584015ef9b2086eecdbd2908b";
    
    //短信配置
    const SMS_ID = "23411852";
    const SMS_SECRET = "8913a859fe272500026e15a22910474d";
    const SMS_ANAME = "实唯科技"; //短信签名

    public $redis;
    public function __construct($host = '127.0.0.1', $port = 6379) {
        date_default_timezone_set('PRC');
        $this->redis = new Redis();
        $this->redis->connect($host, $port);
        //连接远程时授权
        $this->redis->auth("swaylink_123");
    }

    //非现在线告知设备
    public function redis_l(){
        $this->redis->select(0);
        $devArr = $this->redis->keys("*");
		$time = time();
        
        if(!$devArr){
            return false;
        }
        foreach ($devArr as $key => $devid) {
            $this->redis->select(0);
            //(1)轮询设备进行警报处理.对于单台设备,警报处理流程为
            $cur_alarm_no = $this->redis->hget($devid,"cur_alarm_no");
            if($cur_alarm_no=="-1"){
                //没有警报 跳出
                continue;
            }

            $alarm_temp_valid = $this->redis->hget($devid,"alarm_temp_valid");
            $alarm_valid = $this->redis->hget($devid,"alarm_valid");

            if($alarm_temp_valid=="N" || $alarm_valid=="N"){
                continue;
            }

            $alarm_has_send_num = $this->redis->hget($devid,"alarm_has_send_num");
            $alarm_send_num = $this->redis->hget($devid,"alarm_send_num");

            if($alarm_has_send_num>=$alarm_send_num){
               $this->redis->hset($devid,"alarm_temp_valid","N");
               continue;
            }

            $last_alarm_inform_t = $this->redis->hget($devid,"last_alarm_inform_t");
            $intv = $this->redis->hget($devid,"alarm_intv");
            $ts = $time-$last_alarm_inform_t+30;
            $intv_t = $intv*60;
            if($ts<$intv_t){
                continue;
            }

            //更新last_alarm_inform_t,alarm_has_send_num自增1
            $alarm_has_send_num = $this->redis->hget($devid,"alarm_has_send_num");

            $this->redis->hset($devid,"last_alarm_inform_t",$time);
            $this->redis->hset($devid,"alarm_has_send_num",$alarm_has_send_num+1);

            $alarm_has_send_num = $this->redis->hget($devid,"alarm_has_send_num");
            $alarm_send_num = $this->redis->hget($devid,"alarm_send_num");
            if($alarm_has_send_num>=$alarm_send_num){
               $this->redis->hset($devid,"alarm_temp_valid","N");
               continue;
            }
        }
    }

    //初始化
    public function redis_s(){

        $this->redis_l();
        $this->redis_t();
        $this->redis_m();

        $sleep_time = self::SLEEP_TIME;
        sleep($sleep_time);
        $this->redis_s();
    }

    /**
     * 发送警报提醒
     * @return [type] [设备号]
     */
    public function weChat($devid){
        
        $mysqli = new \mysqli(self::DB_HOST,self::DB_USER,self::DB_PWD,self::DB_NAME);
        $sql = "SELECT owner,name FROM dev_info WHERE guid1='{$devid}'";
        $mysqli->query("SET NAMES utf8");
        $result = $mysqli->query($sql);
        $res = $result->fetch_row();
        
        if(0>=$res[0]){
            //此设备未绑定用户
            $result->close();
            return false;
        }

        //取设备共享人 相应的微信地址
        $list = $this->shareAddress($devid);
        if($list){
            foreach ($list as $value) {
                if(!empty($value["weixin"])){
                    //发送警报
                    $this->sendData($value["weixin"],$devid,$res[1]);
                }
            }
        }
    }

    /**
     * 查出设备共享人的相应 地址
     * @param  [type] $devid [description]
     * @return [type]        [description]
     */
    public function shareAddress($dev_id){
        $select = $this->whereRedis($dev_id);
        if(false === $select) return false;
        
        $this->redis->select($select);
        $temp = json_decode($this->redis->hGet($dev_id, 'inform_addr'), true);
        if(false == $temp) return false;
        
        if($temp){
            foreach ($temp as &$v){
                $v = json_decode($v, true);
            }
            unset($v);
            return $temp;
        }else{
            return false;
        }
    }

    /**
     * 发送警报通知
     * @param  [string] $dev_id [设备号]
     * @param  [string] $type [true:异常  false:解除 ]
     * @return [type]         [description]
     */
    public function send_alarm_dev($dev_id,$type=true,$reason=""){

        $mysqli = new \mysqli(self::DB_HOST,self::DB_USER,self::DB_PWD,self::DB_NAME);
        $sql = "SELECT owner,name FROM dev_info WHERE guid1='{$dev_id}'";
        $mysqli->query("SET NAMES utf8");
        $result = $mysqli->query($sql);
        $info = $result->fetch_row();

        if(!$info || $info[0]=="-1"){
            return false;
        }

        $res = $this->shareAddress($dev_id);
        if(!$res){
            return false;
        }

        foreach ($res as $key => $value){

            if(!$value["is_alert"]){
                //判断是否发送警报
                continue;
            }
            //判断是否有效，判断共享期限    et=0 代表无时间限制
            if($value["et"]!=0){
                if($value["st"]>time() || $value["et"]<time()){
                    continue;
                }
            }
            

            switch ($value["alert_type"]) {
                case 'email':
                    if(!empty($value["email"])){

                        if($type){
                            //警报
                            $content = "您的设备".$dev_id."在".date('Y:d:m H:i:s',time())."出现异常。".$reason;
                        }else{
                            //解除
                            $content = "您的设备".$dev_id."在".date('Y:d:m H:i:s',time())."警报解除";
                        }
                        $this->sendEmail($value["email"],$content);
                    }
                    break;
                case 'weixin':
                    if(!empty($value["weixin"])){
                        $this->sendData($value["weixin"],$dev_id,$info[1],$type,$reason);
                    }
                    break;
                case 'sms':
                    if(self::ALARM_SMS){
                        if(!empty($value["sms"])){
                            $this->sendPhone($value["sms"],$dev_id,$type,$reason);
                        }
                    }
                    break;
                case 'all':
                    break;
                default:
                    break;
            }

            if($type){
                //警报
                $son = "设备".$dev_id.' '."出现异常!".' '.$reason.' '.date('H:i:s m/d/Y');
            }else{
                //解除警报
                $son = "设备".$dev_id.' '.date('H:i:s m/d/Y').' '.'警报解除';
            }
            $time = time();
            //推送到站内消息
            $msql = "INSERT INTO `message_table` (`sender`,`sendtime`,`receiver`,`content`,`type`) VALUES ('0',$time,$key,'{$son}','0')";
            $mysqli->query($msql);

            if(self::AlARM_APP){
                // 推送警报消息到app
                $this->sendAlarmToAPP(strval($key), $son);
            }
            unset($son);
        }
    }

    /**
     * 发送邮箱
     * @param  [type] $email   [description]
     * @param  [type] $content [description]
     * @return [type]          [description]
     */
    public function sendEmail($email,$content){

        $smtpserver = "smtp.cdsway.com";//SMTP服务器
        $smtpserverport = "25";//SMTP服务器端口
        $smtpusermail = "swaylink@cdsway.com";//SMTP服务器的用户邮箱
        $smtpemailto = $email;//发送给谁
        $smtpuser = "swaylink@cdsway.com";//SMTP服务器的用户帐号
        $smtppass = "Shiweitech007"; //SMTP服务器的用户密码
        $mailtitle = "实唯物联网";//邮件主题
        $mailtype = "HTML";//邮件格式（HTML/TXT）,TXT为文本邮件
        $from_name = "成都实唯物联网"; //发送人名字

        //这里面的一个true是表示使用身份验证,否则不使用身份验证.
        $smtp = new \smtp($smtpserver,$smtpserverport,true,$smtpuser,$smtppass);
        
        $content = $this->emailCon($content);
        $smtp->debug = false;//是否显示发送的调试信息
        $state = $smtp->sendmail($smtpemailto, $smtpusermail, $mailtitle, $content, $mailtype,"","","",$from_name);
        
        if($state==""){
            return false;
        }
        return true;
    }

    /**
     * 拼装邮件内容
     * @param  [type] $content [description]
     * @return [type]          [description]
     */
    public function emailCon($content){
        $html = '<!DOCTYPE html><html><head><title></title>
                <style type="text/css">body,html,p{padding:0;margin:0;}body{background:#f4f4f4;}.center{width:600px;margin:100px auto 0;}#header{position:relative;width:100%;height:160px;text-align:center;overflow:hidden;}#header a{display: inline-block;height:160px;line-height:158px;overflow:hidden;}#header img.bg{width:100%;position:absolute;top:0;left:0;z-index: -1;}#header img.logo{width:100%;margin-top:40px;}#content{width:100%;height:300px;background:#eee;overflow:hidden;}#content p.c_title{padding-left:60px;margin-top:40px;margin-bottom:10px;color:#595959;}#content .text_box{width:80%;height:160px;border-radius:5px;border:1px solid #dedede;margin:0 auto;background:white;position:relative;}#content .text_box p{padding:14px;text-indent: 2em;} #content .text_box span{font-size:14px;position:absolute;right:20px;bottom:10px;color:#595959;}#footer{width:100%;background:black;height:40px;line-height:40px;text-align: center;color:white;font-size:12px;}</style>
        </head><body><div class="center"><div id="header"><img class="bg" src="http://www.swaylink.cn/static/home/image/background.jpg"><a href="http://www.swaylink.com/"><img class="logo" src="http://www.swaylink.cn/static/home/image/Swaylink.png"></a></div><div id="content"><p class="c_title">尊敬的客户：</p><div class="text_box"><p>'.$content.'</p><span class="luokuan">成都实唯物联网科技</span></div></div><div id="footer">蜀IP备14031015号-4 Copyright@ 2016 Swaylink • All Rights Reserved</div></div></body></html>';

        return $html;
    }

    /**
     * 发送短信
     * @param  [type] $tel    [手机号码]
     * @param  [type] $dev_id [设备号]
     * @param  [type] $type   [true:警报  false:解除]
     * @param  [type] $reason [警报内容]
     * @return [type]         [description]
     */
    public function sendPhone($tel,$dev_id,$type=true,$reason=""){

        $appkey = self::SMS_ID;
        $secret = self::SMS_SECRET;
        $SignName = self::SMS_ANAME;

        if($type){
            //此模板不发送警报内容
            $smsmodelid = "SMS_22120100";
            if($reason){
                //此处中文算1个长度
                $len = mb_strlen($reason,'UTF8');
                if($len<11){
                    //如果警报内容内容大于11长度,则更换发送内容的内容
                    $smsmodelid = "SMS_33445288";
                }
            }
        }else{
            //解除警报
            $smsmodelid = "SMS_22040088";
        }

        $time = date("Y-m-d H:i:s",time());

        $c = new \TopClient;
        $c->appkey = $appkey;
        $c->secretKey = $secret;
        $req = new \AlibabaAliqinFcSmsNumSendRequest;
        $req->setSmsType("normal");
        $req->setSmsFreeSignName($SignName);

        if($reason){
            $len = mb_strlen($reason,'UTF8');
            if($len<11){
                //发出警报且有警报内容
                $req->setSmsParam("{\"name\":\"$dev_id\",\"time\":\"$time\",\"type\":\"$reason\"}");
            }else{
                $req->setSmsParam("{\"name\":\"$dev_id\",\"time\":\"$time\"}");
            }
        }else{
            $req->setSmsParam("{\"name\":\"$dev_id\",\"time\":\"$time\"}");
        }

        $req->setRecNum($tel);
        $req->setSmsTemplateCode($smsmodelid);
        $resp = $c->execute($req);

        $return = $this->object_to_array($resp);
        if(isset($return["sub_code"])){
            return false;
        }else{
            return true;
        }
    }

    /**
     * @param int $name 推送人的uid
     * @param string $content 推送消息主体
     * @return mixed 
     */
    public function sendAlarmToAPP($name,$content){

        $jpush_appid = "db68dc62da2f13d2de754ccd";
        $jpush_appsecret  = "db5f6e04345f24b7112ca022";

        $JPushClient = new \JPush\Client($jpush_appid, $jpush_appsecret);
        $push = $JPushClient->push();
        
        //选择平台all,android,ios
        $push->setPlatform('all');
        
        //选择群体
        try {
            $push->addTag($name);
        }catch (\InvalidArgumentException $e){
        }
        //推送消息格式
        $push->setNotificationAlert($content);
        
        //选择生产环境
        $push->options(array('apns_production' => true));
        
        //正式
        try {
            $string = $push->send();
        }catch (\JPush\Exceptions\JPushException $e){
        }
    }

    /**
     * 对象转数组
     * @param [object] $obj [对象]
     * @return [array] $arr [NULL或ARRAY 返回值]
     */
    public function object_to_array($obj){
        $_arr = is_object($obj) ? get_object_vars($obj) :$obj;
        foreach ($_arr as $key=>$val){
            $val = (is_array($val) || is_object($val)) ? $this->object_to_array($val):$val;
            $arr[$key] = $val;
        }
        return $arr;
    }


    /**
     * 获取access_token
     * @param string $appid 
     * @param string $appsecret
     */
    public function checkAuth(){

        $appid = self::APPID;
        $appsecret = self::APPSECRET;


        $authname = 'wechat_access_token'.$appid;
        if ($rs = $this->getCache($authname))  {
            $token = $rs;
            return $rs;
        }

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;

        $result = $this->http_get($url);
        if ($result)
        {
            $json = json_decode($result,true);
            if (!$json || isset($json['errcode'])) {
                return false;
            }
            $token = $json['access_token'];
            $expire = $json['expires_in'] ? intval($json['expires_in']) : 3600;
            $this->setCache($authname,$token,$expire);
            return $token;
        }
        return false;
    }

    /**
     * 微信发送数据
     * @param  [type]  $openid   [用户openid]
     * @param  [type]  $devid    [设备号]
     * @param  [type]  $dev_name [设备名]
     * @param  boolean $type     [true:异常 false:掉线]
     * @return [type]            [description]
     */
    public function sendData($openid,$devid,$dev_name,$type=true,$reason=""){
        date_default_timezone_set('PRC');
        $time = date("Y-m-d H:i:s",time());

        if($type){
            if($reason){
                $val = $reason;
            }else{
                $val = "出现异常";
            }
            $remark = "请注意：以免给你带来损失!";
        }else{
            $remark = "请注意：此设备警报已解除!";
            $val = "警报解除";
        }

        $data = array(
            "touser"=>$openid,
            "template_id"=>"UEki7S7XI9-uOoDwz8PBiBY7BijUGcZTt71h7H0XXxw",
            "url"=>"",
            "topcolor"=>"#FF0000",
            "data"=>array(
                 "first"=>array(
                     "value"=>"您好,智能设备报告警报信息",
                     "color"=>"#173177"
                 ),
                 "keyword1"=>array(
                     "value"=>$devid,
                     "color"=>"#173177"
                 ),
                 "keyword2"=>array(
                     "value"=>$dev_name,
                     "color"=>"#173177"
                 ),
                 "keyword3"=>array(
                     "value"=>$val,
                     "color"=>"#173177"
                 ),
                 "keyword4"=>array(
                     "value"=>$time,
                     "color"=>"#173177"
                 ),
                 "remark"=>array(
                     "value"=>$remark,
                     "color"=>"#173177"
                 ),
            )
        );
        $fts = $this->sendTemplateMessage($data);

        return $fts;
    }

    /**
     * 发送模板消息
     * @param array $data 消息结构
     * ｛
            "touser":"OPENID",
            "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
            "url":"http://weixin.qq.com/download",
            "topcolor":"#FF0000",
            "data":{
                "参数名1": {
                    "value":"参数",
                    "color":"#173177"    //参数颜色
                    },
                "Date":{
                    "value":"06月07日 19时24分",
                    "color":"#173177"
                    },
                "CardNumber":{
                    "value":"0426",
                    "color":"#173177"
                    },
                "Type":{
                    "value":"消费",
                    "color":"#173177"
                    }
            }
        }
     * @return boolean|array
     */
    public function sendTemplateMessage($data){

        $token = $this->checkAuth();

        if (!$token){
            return false;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
        $result = $this->http_post($url,$this->json_encode($data));
        if($result){
            $json = json_decode($result,true);
            if (!$json || !empty($json['errcode'])) {
                
                if($json['errcode']=="40001"){
                    //token过期,删除原先的
                    $this->resetAuth();
                    //然后重新调用本方法
                    $res = $this->sendTemplateMessage($data);
                    
                    return $res;
                }

                return false;
            }
            return $json;
        }
        return false;
    }

    /**
     * 删除验证数据
     * @param string $appid
     */
    public function resetAuth(){
        $appid = self::APPID;
        
        $authname = 'wechat_access_token'.$appid;
        
        $this->redis->select(3);
        $this->redis->delete($authname);

        return true;
    }

    /**
     * 微信api不支持中文转义的json结构
     * @param array $arr
     */
    public function json_encode($arr) {
        if (count($arr) == 0) return "[]";
        $parts = array ();
        $is_list = false;
        //Find out if the given array is a numerical array
        $keys = array_keys ( $arr );
        $max_length = count ( $arr ) - 1;
        if (($keys [0] === 0) && ($keys [$max_length] === $max_length )) { //See if the first key is 0 and last key is length - 1
            $is_list = true;
            for($i = 0; $i < count ( $keys ); $i ++) { //See if each key correspondes to its position
                if ($i != $keys [$i]) { //A key fails at position check.
                    $is_list = false; //It is an associative array.
                    break;
                }
            }
        }
        foreach ( $arr as $key => $value ) {
            if (is_array ( $value )) { //Custom handling for arrays
                if ($is_list)
                    $parts [] = $this->json_encode ( $value ); /* :RECURSION: */
                else
                    $parts [] = '"' . $key . '":' . $this->json_encode ( $value ); /* :RECURSION: */
            } else {
                $str = '';
                if (! $is_list)
                    $str = '"' . $key . '":';
                //Custom handling for multiple data types
                if (!is_string ( $value ) && is_numeric ( $value ) && $value<2000000000)
                    $str .= $value; //Numbers
                elseif ($value === false)
                $str .= 'false'; //The booleans
                elseif ($value === true)
                $str .= 'true';
                else
                    $str .= '"' . addslashes ( $value ) . '"'; //All other things
                // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
                $parts [] = $str;
            }
        }
        $json = implode ( ',', $parts );
        if ($is_list)
            return '[' . $json . ']'; //Return numerical JSON
        return '{' . $json . '}'; //Return associative JSON
    }

    /**
     * POST 请求
     * @param string $url
     * @param array $param
     * @param boolean $post_file 是否文件上传
     * @return string content
     */
    public function http_post($url,$param,$post_file=false){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach($param as $key=>$val){
                $aPOST[] = $key."=".urlencode($val);
            }
            $strPOST =  join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($oCurl, CURLOPT_POST,true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }

    /**
     * GET 请求
     * @param string $url
     */
    private function http_get($url){
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }

    /**
     * 设置缓存，按需重载
     * @param string $cachename
     * @param mixed $value
     * @param int $expired
     * @return boolean
     */
    public function setCache($cachename,$value,$expired){

        $this->redis->select(3);

        $this->redis->set($cachename,$value);
        $this->redis->expire($cachename,$expired);

        return false;
    }

    /**
     * 获取缓存，按需重载
     * @param string $cachename
     * @return mixed
     */
    public function getCache($cachename){
        
        $this->redis->select(3);
        $res = $this->redis->get($cachename);
        
        if($res){
           return $res;
        }else{
           return false;
        }
    }

    /**
     * 判断设备在redis几号数据库
     * @param string $dev_id 设备号
     * @return mixed
     * 
     * */
    public function whereRedis($dev_id) {
        $this->redis->select(0);
        $r0 = $this->redis->exists($dev_id);
        if($r0){
            //在0号数据库
            return 0;
        }
        
        $this->redis->select(2);
        $r2 = $this->redis->exists($dev_id);
        if($r2){
            //在2号数据库
            return 2;
        }else{
            //不在redis中,代表设备掉线
            return false;
        }
    }


    /**
     * 发送
     * @param  [type] $devid [设备号]
     * @param  [type] $type  [false:解除  true：异常]
     * @return [type]        [description]
     */
    public function sendA($devid,$type){
        
        if($type){
            $select = $this->whereRedis($devid);
            if(false === $select) return false;
            
            $this->redis->select($select);
            $reason = $this->redis->hget($devid,"alarm_msg");
            //发送警报
            $this->send_alarm_dev($devid,true,$reason);

            return true;
        }else{

            $this->send_alarm_dev($devid,false);
            return true;
        }

        return false;
    }

    /**
     * 创建文件填写内容 并保存
     * @param  [string] $name    [文件名]
     * @param  [string] $content [内容]
     * @param  [string] $path    [保存路径,默认:upload_file/] 
     * @param  [string] $type    [true：创建文件保存  false:写日志 ]
     */
    public function saveFile($name,$content,$path="/",$type=true){
        // return true;
        // 创建文件夹并给777的权限（所有权限）
        // if (!file_exists($path)){
        //     mkdir($path,0777,true);  
        // }

        $file = $path.$name;

        if($type){
            $myfile = fopen($file,"w");
        }else{
            $myfile = fopen($file,"a+");
        }
        
        fwrite($myfile, $content);
        fclose($myfile);
    }

}

$devid = $argv[1];
$type = $argv[2];

if(!$devid){
    exit;
}

if($type==1){
    $type = true;
}elseif ($type==2) {
    $type = false;
}

$work = new MRedis();
$work->sendA($devid,$type);

?>